package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyXiongMaoHaoYong;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeXiongMaoHaoYong;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 安心分期&熊猫好用8位全
 *
 * @author 江小游
 */
@ApiPlan(productId = "237", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatXiongMaoHaoYongPhoneMd5Convert implements ApiPlatformPhoneMaskConvertHandler {
    private static final String KEY = "TZOWD2UT91Z8UKM4";
    private static final String CHANNEL = "TZOWD2UT91Z8UKM40H0WU9KI7CP48M91";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        //  撞库流程
        ApiPlatDataExchangeXiongMaoHaoYong apiPlatDataExchange = new ApiPlatDataExchangeXiongMaoHaoYong();
        // 扩展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        // 撞库id
        apiPlatDataExchange.setOrderNo(apiDataExchangeParameter.getReqId());
        // md5
        apiPlatDataExchange.setPhoneMd5(apiDataExchangeParameter.getPhoneMd5());
        // 掩码
        apiPlatDataExchange.setPhoneMask(apiDataExchangeParameter.getPhoneMask());
        // 年龄
        apiPlatDataExchange.setAge(apiFieldConverter.getAgeInt());
        // 姓名md5
        apiPlatDataExchange.setNameMd5(MD5.create().digestToBase64Str(apiDataExchangeParameter.getUserName()));
        // 城市
        apiPlatDataExchange.setCity(apiDataExchangeParameter.getCity());
        // 城市编码
        apiPlatDataExchange.setCityCode(apiDataExchangeParameter.getAreaCode());
        //  性别 1男 2女
        Integer sex = ChooseEq.create(apiDataExchangeParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        apiPlatDataExchange.setSex(sex);
        // 社保 (0-> 无 1->小于6个月 2->大于6个月)
        Integer socialSecurity = ChooseEq.create(apiDataExchangeParameter.getSocialSecurity())
                .when("1", 0)
                .when("2", 1)
                .when("3", 2)
                .when("4", 1)
                .end(0);
        apiPlatDataExchange.setSocialSecurity(socialSecurity);
        // 公积金 (0-> 无 1->小于6个月 2->大于6个月)
        Integer providentFund = ChooseEq.create(apiDataExchangeParameter.getProvidentFund())
                .when("1", 0)
                .when("2", 1)
                .when("3", 2)
                .when("4", 1)
                .end(0);
        apiPlatDataExchange.setProvidentFund(providentFund);
        // 车(1->无 2->有)
        Integer carInfo = ChooseEq.create(apiDataExchangeParameter.getCarInfo())
                .when("1", 1)
                .when("2", 2)
                .when("3", 2)
                .when("4", 2)
                .end(1);
        apiPlatDataExchange.setCar(carInfo);
        // 房产情况 (1->无 2->有)
        Integer realEstateInfo = ChooseEq.create(apiDataExchangeParameter.getRealEstateInfo())
                .when("1", 1)
                .when("2", 2)
                .when("3", 2)
                .when("4", 2)
                .when("5", 2)
                .when("6", 2)
                .end(1);
        apiPlatDataExchange.setHouse(realEstateInfo);
        // 保险单( 0->无 1->一年以下 2->一年到两年 3->两年以上)
        Integer insurancePolicy = ChooseEq.create(apiDataExchangeParameter.getInsurancePolicy())
                .when("1", 0)
                .when("2", 1)
                .when("3", 2)
                .when("4", 1)
                .end(0);
        apiPlatDataExchange.setInsurancePolicy(insurancePolicy);
        // 芝麻分(输入)
        apiPlatDataExchange.setSesameSeeds(apiFieldConverter.getSesameCreditNumber());
        // 职业身份 (1->上班族 2->公务员/事业单位 3->国企  4->私营业主 5->个体户 6->其他)
        Integer career = ChooseEq.create(apiDataExchangeParameter.getCareer())
                .when("1", 1)
                .when("2", 6)
                .when("3", 4)
                .when("4", 2)
                .when("5", 5)
                .end(1);
        apiPlatDataExchange.setCareer(career);
        // 信用卡 (0->无 1->6个月以下 2->6个月以上)
        Integer creditLimit = ChooseEq.create(apiDataExchangeParameter.getCreditLimit())
                .when("1", 0)
                .when("2", 1)
                .when("3", 1)
                .when("4", 2)
                .when("5", 2)
                .when("6", 1)
                .end(0);
        apiPlatDataExchange.setCreditCard(creditLimit);
        // 学历 (1->大专及以下 2->本科及以上)
        Integer educationAttainment = ChooseEq.create(apiDataExchangeParameter.getEducationAttainment())
                .when("1", 1)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 2)
                .when("6", 2)
                .end(1);
        apiPlatDataExchange.setEducation(educationAttainment);
        // 打卡工资 (1->5K到1W 2->1W以上)
        Integer monthlySalary = ChooseEq.create(apiDataExchangeParameter.getMonthlySalary())
                .when("1", 1)
                .when("2", 1)
                .when("3", 2)
                .when("4", 2)
                .when("5", 2)
                .end(1);
        apiPlatDataExchange.setMonthlyIncome(monthlySalary);
        // 借款额度 输入 单位 万
        Integer loanAmount = ChooseEq.create(apiDataExchangeParameter.getLoanAmount())
                .when("1", 3)
                .when("2", 10)
                .when("3", 20)
                .when("4", 30)
                .end();
        apiPlatDataExchange.setBorrowingLimit(loanAmount);
        // 渠道id
        apiPlatDataExchange.setChannelIdentification(CHANNEL);
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatDataExchange));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelIdentification", CHANNEL);
            newMap.put("data", data);
        });
        return JsonUtils.toJson(map);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        //  进件流程
        ApiPlatApplyXiongMaoHaoYong apiPlatApply = new ApiPlatApplyXiongMaoHaoYong();
        // 扩展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        //  进件id
        apiPlatApply.setOrderNo(apiApplyParameter.getReqId());
        // 手机号
        apiPlatApply.setPhone(apiApplyParameter.getPhone());
        // 姓名
        apiPlatApply.setName(apiApplyParameter.getUserName());
        // 年龄
        apiPlatApply.setAge(apiFieldConverter.getAgeInt());
        // 城市
        apiPlatApply.setCity(apiApplyParameter.getCity());
        // 城市编码
        apiPlatApply.setCityCode(apiApplyParameter.getAreaCode());
        //  性别 1男 2女
        Integer sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        apiPlatApply.setSex(sex);
        // 社保 (0-> 无 1->小于6个月 2->大于6个月)
        Integer socialSecurity = ChooseEq.create(apiApplyParameter.getSocialSecurity())
                .when("1", 0)
                .when("2", 1)
                .when("3", 2)
                .when("4", 1)
                .end(0);
        apiPlatApply.setSocialSecurity(socialSecurity);
        // 公积金 (0-> 无 1->小于6个月 2->大于6个月)
        Integer providentFund = ChooseEq.create(apiApplyParameter.getProvidentFund())
                .when("1", 0)
                .when("2", 1)
                .when("3", 2)
                .when("4", 1)
                .end(0);
        apiPlatApply.setProvidentFund(providentFund);
        // 车(1->无 2->有)
        Integer carInfo = ChooseEq.create(apiApplyParameter.getCarInfo())
                .when("1", 1)
                .when("2", 2)
                .when("3", 2)
                .when("4", 2)
                .end(1);
        apiPlatApply.setCar(carInfo);
        // 房产情况 (1->无 2->有)
        Integer realEstateInfo = ChooseEq.create(apiApplyParameter.getRealEstateInfo())
                .when("1", 1)
                .when("2", 2)
                .when("3", 2)
                .when("4", 2)
                .when("5", 2)
                .when("6", 2)
                .end(1);
        apiPlatApply.setHouse(realEstateInfo);
        // 保险单( 0->无 1->一年以下 2->一年到两年 3->两年以上)
        Integer insurancePolicy = ChooseEq.create(apiApplyParameter.getInsurancePolicy())
                .when("1", 0)
                .when("2", 1)
                .when("3", 2)
                .when("4", 1)
                .end(0);
        apiPlatApply.setInsurancePolicy(insurancePolicy);
        // 芝麻分(输入)
        apiPlatApply.setSesameSeeds(apiFieldConverter.getSesameCreditNumber());
        // 职业身份 (1->上班族 2->公务员/事业单位 3->国企  4->私营业主 5->个体户 6->其他)
        Integer career = ChooseEq.create(apiApplyParameter.getCareer())
                .when("1", 1)
                .when("2", 6)
                .when("3", 4)
                .when("4", 2)
                .when("5", 5)
                .end(1);
        apiPlatApply.setCareer(career);
        // 信用卡 (0->无 1->6个月以下 2->6个月以上)
        Integer creditLimit = ChooseEq.create(apiApplyParameter.getCreditLimit())
                .when("1", 0)
                .when("2", 1)
                .when("3", 1)
                .when("4", 2)
                .when("5", 2)
                .when("6", 1)
                .end(0);
        apiPlatApply.setCreditCard(creditLimit);
        // 学历 (1->大专及以下 2->本科及以上)
        Integer educationAttainment = ChooseEq.create(apiApplyParameter.getEducationAttainment())
                .when("1", 1)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 2)
                .when("6", 2)
                .end(1);
        apiPlatApply.setEducation(educationAttainment);
        // 打卡工资 (1->5K到1W 2->1W以上)
        Integer monthlySalary = ChooseEq.create(apiApplyParameter.getMonthlySalary())
                .when("1", 1)
                .when("2", 1)
                .when("3", 2)
                .when("4", 2)
                .when("5", 2)
                .end(1);
        apiPlatApply.setMonthlyIncome(monthlySalary);
        // 借款额度 输入 单位 万
        Integer loanAmount = ChooseEq.create(apiApplyParameter.getLoanAmount())
                .when("1", 3)
                .when("2", 10)
                .when("3", 20)
                .when("4", 30)
                .end();
        apiPlatApply.setBorrowingLimit(loanAmount);
        apiPlatApply.setChannelIdentification(CHANNEL);
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatApply));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelIdentification", CHANNEL);
            newMap.put("data", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        //  进件返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();

    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        //  根据文档响应判断
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        //  获取属性值
        JSONArray resData = JsonUtils.get(respJson).getJSONArray("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();
        for (int i = 0; i < resData.size(); i++) {
            JSONObject item = resData.getJSONObject(i);
            if (ValidParam.isNotNull(item)) {
                BigDecimal price = item.getBigDecimal("callBackPrice");
                String logo = item.getString("agencyLogoUrl");
                String companyName = item.getString("loanName");
                String productName = item.getString("productName");

                //  获取协议内容
                List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
                    //  获取协议
                    JSONArray listProtocolResult = item.getJSONArray("authorizationAgreement");
                    IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
                        JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                        ApiProtocol protocol = new ApiProtocol();
                        protocol.setProtocolName(protocolObject.getString("name"));
                        protocol.setProtocolUrl(protocolObject.getString("url"));
                        newList.add(protocol);
                    });
                });
                //  返回转换内容
                RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();

                result.setPrice(price);
                result.setLogoPath(logo);
                result.setDisplayName(companyName);
                result.setProductName(productName);
                result.setProtocolList(protocolList);

                listRespPlatformPhoneMaskDataExchange.add(result);
            }
        }
        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return null;
    }
}
